package org.halo.trade.data.sina;


import java.io.IOException;





import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.util.EntityUtils;

public class DownloadFileResponseHandler implements ResponseHandler<Boolean>
{
	final private String filename;
	final private HttpRequestBase httprequest;
	public DownloadFileResponseHandler(HttpRequestBase httprequest,String filename)
	{
		this.filename=filename;		
		this.httprequest=httprequest;
	}
	@Override
	public Boolean handleResponse(final HttpResponse response) throws ClientProtocolException, IOException
	{
		int status = response.getStatusLine().getStatusCode();
		HttpEntity entity = response.getEntity();
		byte[] ret=entity != null ? EntityUtils.toByteArray(entity) : null;
		EntityUtils.consume(entity);
		
//		try
//		{
//			httprequest.releaseConnection();
//		} catch (Exception e)
//		{
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		if (status >= 200 && status < 300)
		{
			if(filename!=null)
			{
				Utils.writFile(filename, ret);
//				Utils.readbytes(ret);
				return true;
			}
			
		} else
		{
			throw new ClientProtocolException("Unexpected response status: " + status);
		}
		return false;
	}
};